﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinServer
{
    public partial class FormClient : Form
    {
        /// 委托接收服务端发送的数据
        /// <param name="receiveBuffer"></param>

        public delegate void ReceiveHandle(byte[] receiveBuffer);

        /// 接收服务端发送的数据事件

        public event ReceiveHandle ReceiveDataEvent;
    
        /// 客户端连接 

        TcpClient tcpClient;

        ManualResetEvent manualWait = new ManualResetEvent(false);     

        /// 是否已连接    

        bool isConnect = false;

        /// 服务端与客户端send、receive所使用的流

        NetworkStream networkStream;

        /// 接收线程

        Thread receiveThread;   

        /// 服务器地址和端口 如 192.168.0.23:3456       

        string serverIpAndPort = string.Empty;
        public FormClient()
        {
            InitializeComponent();
        }

        private void btnOnline_Click(object sender, EventArgs e)
        {
            if (isConnect)
            {
                MessageBox.Show("已连接到服务端");
                return;
            }
            string ipAddress = txtIP.Text;
            int port = int.Parse(txtPort.Text);
            tcpClient = new TcpClient();
            try
            {
                serverIpAndPort = string.Empty;

                bool connectSuccess = ConnectServer(ipAddress, port);
                if (connectSuccess)
                {
                    rtxtInfo.AppendText(string.Format("已连接到服务器，服务器IP：{0},端口：{1}\r\n", ipAddress, port));

                    //订阅服务端发送过来的数据的事件

                    ReceiveDataEvent -= FormClient_ReceiveDataEvent;

                    ReceiveDataEvent += FormClient_ReceiveDataEvent;

                    receiveThread = new Thread(ReceiveProcess);
                    receiveThread.IsBackground = true;
                    receiveThread.Start();

                }
                else
                {
                  // MessageBox.Show("连接服务端失败");

                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "连接失败");
            }
        }

        private void btnOffLine_Click(object sender, EventArgs e)
        {
            isConnect = false;
            try
            {

                if (tcpClient != null)
                {

                    tcpClient.Close();

                }
                if (networkStream != null)
                {

                    networkStream.Close();

                }
            }
            catch (Exception ex)
            {
                 MessageBox.Show(ex.Message, "关闭连接出错");
            }

        }
        int count = 0;

        private void FormClient_ReceiveDataEvent(byte[] buffer)
        {
            count++;
            string recieveContent = Encoding.GetEncoding("gbk").GetString(buffer);

            string message = serverIpAndPort + "说 " + recieveContent;

            this.Invoke(new MethodInvoker(() =>
            {
                rtxtInfo.AppendText(message + "\r\n");

            }));

            if (count >= 100)
            {
                count = 0;
            }

        }

        /// 异步连接服务端
        /// <param name="serverIP">服务端IP地址</param>
        /// <param name="port">服务端端口</param>
        /// <returns></returns>

        private bool ConnectServer(string serverIP, int port)
        {
            isConnect = false;
            manualWait.Reset();

            tcpClient.BeginConnect(serverIP, port, new AsyncCallback(RequestCallback), tcpClient);
            if (manualWait.WaitOne(2000, false))

            {
                if (isConnect)
                {
                    serverIpAndPort = string.Format("{0}:{1}", serverIP, port);
                    networkStream = tcpClient.GetStream();
                    return true;

                }
                return false;

            }
            else
            {
                return false;
                //throw new Exception("回调函数未正常返回，请确认超时参数正确");
            }

        }

        /// 异步连接回调函数     
        /// <param name="asyncResult"></param>
        private void RequestCallback(IAsyncResult asyncResult)
        {
            isConnect = false;
            try
            {
                TcpClient client = asyncResult.AsyncState as TcpClient;
                if (client != null)
                {
                    client.EndConnect(asyncResult);
                    isConnect = true;

                }
            }
            catch (Exception ex)
            {
                isConnect = false;
                MessageBox.Show("连接服务器出现异常：" + ex.Message, "尝试连接服务器");

            }
            finally
            {

                manualWait.Set();

            }
        }
        private void ReceiveProcess()
        {
            try
            {
                while (isConnect)
                {
                    if (networkStream != null && networkStream.CanRead)
                    {

                        //冲刷，强制刷新缓冲区，如果不调用Flush函数，接收的内容将一直停留在缓冲区。Flush函数就是从缓冲区拿到数据

                        networkStream.Flush();

                        byte[] buffer = new byte[10240];

                        //networkStream.ReadTimeout = 10000;

                        int byteCount = networkStream.Read(buffer, 0, buffer.Length);
                        if (byteCount > 0)
                        {
                            byte[] destBuffer = new byte[byteCount];

                            Array.Copy(buffer, destBuffer, byteCount);

                            if (ReceiveDataEvent != null)
                            {
                                ReceiveDataEvent(destBuffer);

                            }
                        }
                    }
                    Thread.Sleep(1);
                }
            }

            catch (Exception ex)
            {
                isConnect = false;
                MessageBox.Show(ex.Message, "读取接收数据出错");
            }

        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            if (!isConnect)
            {
                MessageBox.Show("请先连接服务端！", "提示");
                return;
            }
            if (rtxtSendMessage.Text.Length == 0)
            {
                MessageBox.Show("请输入发送内容！", "提示");
                rtxtSendMessage.Focus();
                return;
            }

            //SuperSocket默认发送约束为结尾是： \r\n         

            byte[] buffer = Encoding.GetEncoding("gbk").GetBytes(txtBeginMark.Text.Trim() + rtxtSendMessage.Text+txtEndMark.Text.Trim());
            //Array.Copy(buffer)
            try
            {
                networkStream.WriteTimeout = 100;
                if (networkStream.CanWrite)
                {

                    networkStream.Write(buffer, 0, buffer.Length);

                }
            }
            catch (Exception ex)
            {
                isConnect = false;
                MessageBox.Show(ex.Message, "发送数据出错");

            }

        }

    }
 
}
